package com.vic.delayedqueue.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * rabbitmq的基于插件的延时队列配置
 * 1 声明通用交换机、通用路由键、通用队列、通用队列绑定到通用交换机。
 * 2 在声明通用队列时，指定死信交换机、死信路由键。注意：这里不要指定队列的TTL。
 */
//@Configuration
public class DelayedQueue3Config {

    // 延时交换机
    public static final String DELAYED_EXCHANGE = "delayed_exchange";

    // 延时队列
    public static final String DELAYED_QUEUE = "delayed_queue";
    // 延时路由键
    public static final String DELAYED_ROUTING_KEY = "delayed.routingkey";

    // 自定义交换机，这里声明一个延时交换机
    @Bean("delayed_exchange")
    public CustomExchange delayedExchange() {
        Map<String, Object> args = new HashMap<>();
        // 自定义交换机的类型
        args.put("x-delayed-type", "direct");
        return new CustomExchange(DELAYED_EXCHANGE, "x-delayed-message", true, false, args);
    }

    // 声明延时队列，也就是一个普通队列
    @Bean("delayed_queue")
    public Queue delayedQueue() {
        return new Queue(DELAYED_QUEUE);
    }

    // 声明 延时队列 绑定 延时交换机
    @Bean
    public Binding delayedQueueBindingDelayedExchange(@Qualifier("delayed_queue") Queue queue, @Qualifier("delayed_exchange") CustomExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(DELAYED_ROUTING_KEY).noargs();
    }

}